package com.htdata.iiot.api.pojo;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.htdata.iiot.utils.ApiKey;
import com.htiiot.common.db.DbConnectionPool;
import com.htiiot.common.db.JDBCUtils;

public class DeviceDAO {
	private static Logger logger = LogManager.getLogger(DeviceDAO.class);

	

    public static boolean createDevice(Device device) throws SQLException{
		String sql = "insert into thing_device (name,tenant_id,location,country,province,"
				+ "city,county,brand,model,type,serial_number) values(?,4557,?,'中国',?,?,?,?,?,0,?)";
		DbConnectionPool pool = DbConnectionPool.getPool();
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		int deviceId = -1;
		int ret = -1;
		try {
			conn = pool.getConnection();
			conn.setAutoCommit(false);
			ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
			ps.setString(1, device.getName());
			ps.setString(2, device.getLocation());
			ps.setString(3, device.getProv());
			ps.setString(4, device.getCity());
			ps.setString(5, device.getCounty());
			ps.setString(6, device.getBrand());
			ps.setString(7, device.getModel());
			ps.setString(8, device.getSerNum());
			ps.executeUpdate();
			rs = ps.getGeneratedKeys();
			if(rs.next()){
				deviceId = rs.getInt(1);
			}

			String apikey = ApiKey.genKeyForDevice(deviceId);
			String updatesql = "update thing_device set api_key = '"+apikey + "' where id = " + deviceId;
			ps = conn.prepareStatement(updatesql);
			ret = ps.executeUpdate();
			device.setId(deviceId);
			return deviceId>0;
		} catch (SQLException e) {
			conn.rollback();
			logger.error(e.getMessage());
			throw e;
		} finally {
			conn.commit();
			JDBCUtils.close(ps, rs, conn);
		}


    }
    
    

    public static Map<String, String> createComponent(Metric metric) throws SQLException {
      DbConnectionPool pool = DbConnectionPool.getPool();
      Connection conn = null;
      PreparedStatement ps = null;
      ResultSet rs = null;
      conn = pool.getConnection();
      Map<String, String> mapResult = new HashMap<String, String>();
      int sum = -1;
      String searchSql = null;
      try
      {
        conn.setAutoCommit(false);

        int componentId = -1;
        String sql1 = "insert into thing_component ("
        		+ "create_time,name,struct_id,tenant_id,public,status,deleted)  "
        		+ "values (now(), "
        		+ "?,?,4557,0,0,false)";

        ps = conn.prepareStatement(sql1, Statement.RETURN_GENERATED_KEYS);
        ps.setString(1, metric.getComponentName());
        ps.setInt(2, metric.getDid());
        ps.executeUpdate();
        rs = ps.getGeneratedKeys();
        if (rs.next()) {
          componentId = rs.getInt(1);
        }
        if (componentId == -1) {
          throw new SQLException();
        }

        int data_stream_id = -1;
        String sql2 = "insert into thing_data_stream "
        		+ "(create_time, name, tenant_id, component_id,type, status,deleted, unit,min,max) "
        		+ "values (now(),"
        		+ "?,4557,?,0,0,0,?,?,?)";


        ps = conn.prepareStatement(sql2, Statement.RETURN_GENERATED_KEYS);
        ps.setString(1, metric.getName());
        ps.setInt(2, componentId);
        ps.setString(3, metric.getUnit());
        ps.setDouble(4, metric.getMin());
        ps.setDouble(5, metric.getMax());
        ps.executeUpdate();
        rs = ps.getGeneratedKeys();
        if (rs.next()) {
          data_stream_id = rs.getInt(1);
        }

        if (data_stream_id == -1) {
          throw new SQLException();
        }

        int device_component_rel_ret = -1;
        String apikey = null;
        int device_component_rel_id;
          device_component_rel_id = -1;
          String sql4 = "insert into thing_device_component_rel (device_id,component_id,status,deleted,create_time) values(?,?,0,false,now())";
          ps = conn.prepareStatement(sql4, Statement.RETURN_GENERATED_KEYS);
          ps.setInt(1, metric.getDid());
          ps.setInt(2, componentId);
          ps.executeUpdate();
          rs = ps.getGeneratedKeys();
          if (rs.next()) {
            device_component_rel_id = rs.getInt(1);
          }
          if (device_component_rel_id == -1) {
            throw new SQLException();
          }

          apikey = ApiKey.genKeyForComponent(device_component_rel_id);
          String updatesql = "update thing_device_component_rel set api_key = '" + apikey + "' where id = " + device_component_rel_id;
          ps = conn.prepareStatement(updatesql);
          device_component_rel_ret = ps.executeUpdate();
          if (device_component_rel_ret == 0) {
            throw new SQLException();
          }
        mapResult.put("componentId", componentId + "");
        mapResult.put("dataStreamId", data_stream_id + "");
        mapResult.put("apikey", apikey);
        return mapResult;
      } catch (SQLException e) {
        conn.rollback();
        logger.error(e.getMessage());
        throw e;
      } finally {
        conn.commit();
        JDBCUtils.close(ps, rs, conn);
      }
    }

}
